/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin			*/
/*	Project:	GlbCloud			*/
/*	Author:		gong_libin			*/
/*	Date:		2012_01_03			*/
/*	File:		MrMtLock.cpp			*/
/********************************************************/

#include "MrMtLock.h"

CMrMtLock::CMrMtLock()
{
}

CMrMtLock::~CMrMtLock()
{
}

int CMrMtLock::MrLockMalloc(void* pLock)
{
	if (NULL == pLock) {
		CMrLock::m_pLock = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
		if (NULL == CMrLock::m_pLock) {
			return MR_FAILURE;
		}
	}
	else {
		CMrLock::m_pLock = (pthread_mutex_t*)pLock;
	}

	return MR_SUCCESS;
}

int CMrMtLock::MrLockCreate(bool bShared)
{
	pthread_mutexattr_t stAttr;

	if (NULL != CMrLock::m_pLock) {
		if (MR_SUCCESS !=  pthread_mutexattr_init(&stAttr)) {
			MR_ERROR("%s\n", strerror(errno));
			return MR_FAILURE;
		}

		if (true == bShared) {
			if (MR_SUCCESS != pthread_mutexattr_setpshared(&stAttr, PTHREAD_PROCESS_SHARED)) {
				MR_ERROR("%s\n", strerror(errno));
				return MR_FAILURE;
			}
		}

		if (MR_SUCCESS != pthread_mutex_init((pthread_mutex_t*)CMrLock::m_pLock, &stAttr)) {
			MR_ERROR("%s\n", strerror(errno));
			return MR_FAILURE;
		}

		if (MR_SUCCESS != pthread_mutexattr_destroy(&stAttr)) {
			MR_ERROR("%s\n", strerror(errno));
			return MR_FAILURE;
		}
	}
	else {
		return MR_FAILURE;
	}

	return MR_SUCCESS;
}

int CMrMtLock::MrLockDelete()
{
	if (NULL != CMrLock::m_pLock) {
		if (MR_SUCCESS != pthread_mutex_destroy((pthread_mutex_t*)CMrLock::m_pLock)) {
			MR_ERROR("%s\n", strerror(errno));
			return MR_FAILURE;
		}
	}

	return MR_SUCCESS;
}
